package org.example.concurrent;

import java.util.concurrent.Semaphore;

public class SemaphoreExample {

    private final Semaphore semaphore = new Semaphore(3); // 允许最多三个线程同时访问

    public void accessResource() {
        try {
            semaphore.acquire(); // 获取一个许可
            System.out.println(Thread.currentThread().getName() + " is accessing the resource.");
            // 执行资源访问的代码
            Thread.sleep(1000); // 模拟资源访问耗时
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            semaphore.release(); // 释放许可
        }
    }

    public static void main(String[] args) {
        SemaphoreExample example = new SemaphoreExample();
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> example.accessResource(), "Thread-" + i);
            thread.start();
        }
    }
}